import glob
import os

import fitz


def get_images_glob(path):
    """获取指定路径下所有jpg和png图片"""
    # 定义图片扩展名模式
    patterns = ['*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp']

    image_files = []
    for pattern in patterns:
        # 使用os.path.join确保路径正确性
        full_pattern = os.path.join(path, pattern)
        image_files.extend(glob.glob(full_pattern))

    return image_files


def is_directory(path):
    """
    判断给定路径是否为文件夹

    Args:
        path (str): 要检查的路径

    Returns:
        bool: 如果是文件夹返回True，否则返回False
    """
    # 方法1：使用os.path.isdir()
    if os.path.exists(path):
        return os.path.isdir(path)
    return False


# 合并
def merge(docs, path, name):
    doc3 = fitz.open()
    for doc in docs:
        img_doc = fitz.open(doc)
        pdf_bytes = img_doc.convert_to_pdf()
        img_pdf = fitz.open("pdf", pdf_bytes)
        doc3.insert_pdf(img_pdf)

    doc3.save(path + '\\' + name)
    # print("操作完成，文件以保存在:\n"+Doc+"(合并).pdf")
    m1 = "操作完成，文件以保存在:\n" + path + '\\' + name
    return m1


def merge_path(sourcePath, targetPath, name):
    if type(sourcePath) == list or not is_directory(sourcePath):
        if type(sourcePath) == list:
            merge(sourcePath, targetPath, name)
        else:
            merge([sourcePath], targetPath, name)
    else:
        arr = get_images_glob(sourcePath)
        merge(arr, targetPath, name)
        print(arr)


if __name__ == '__main__':
    path = 'C:\\Users\\admin\\Desktop\\测试'
    if type(path) == list or not is_directory(path):
        if type(path) == list:
            merge(path, path[0][0:path[0].rfind("\\")], "合并.pdf")
        else:
            merge([path], path[0:path.rfind("\\")], "合并.pdf")
    else:
        docs = get_images_glob(path)
        merge(docs, path, path[path.rfind("\\") + 1:len(path)] + '.pdf')
        print(docs)
